package com.springboot.controller;

import com.springboot.config.MyConfig;
import com.springboot.event.LoginEvent;
import com.springboot.event.LoginExitEvent;
import com.springboot.listener.LoginExitListener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController implements ApplicationContextAware {


    private ApplicationContext context;

    @Autowired
    private MyConfig myConfig;

    @RequestMapping("/test")
    public String test(){
        System.out.println("id="+myConfig.getId());
        System.out.println("name="+myConfig.getName());
        return "test";
    }
    @RequestMapping("/login")
    public String  login(@RequestParam(name = "userName")String userName){
        context.publishEvent(new LoginEvent(userName));
        System.out.println("开始登录");
        return "login success!";
    }

    @RequestMapping("/exit")
    public String  exit(@RequestParam(name = "userName")String userName){
        //发布一个退出登录的事件
        context.publishEvent(new LoginExitEvent(userName));
        System.out.println("退出登录。。。");
        return "login success!";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println(applicationContext);
        this.context = applicationContext;
        AbstractApplicationContext applicationContext1 = (AbstractApplicationContext) applicationContext;
        applicationContext1.addApplicationListener( new LoginExitListener());
    }
}
